from django.db import models
from django.db.models import signals
from django.conf import settings

import os

import PIL
from PIL import Image

#from tvapi.thetvdb.views import GenerateThumbnail

class ServerSettings(models.Model):
    lastUpdated = models.CharField(max_length=20)
    date_added = models.DateTimeField(auto_now_add=True, editable=False)
    last_modified = models.DateTimeField(auto_now=True, editable=False)
    
    class Meta:
        get_latest_by = "last_modified"

# Create your models here.
class Language(models.Model):
    id = models.IntegerField(primary_key=True)
    abbreviation = models.CharField(max_length=10, unique=True, db_index=True)
    name = models.CharField(max_length=50) 
    date_added = models.DateTimeField(auto_now_add=True, editable=False)
    last_modified = models.DateTimeField(auto_now=True, editable=False)
    
    def __unicode__(self):
        return u'%s' % self.name

    class Meta:
        get_latest_by = "last_modified"
        ordering = ["abbreviation",]

def get_image_path(instance, filename):
    return os.path.join("%s%s" % ("thetvdb/banners/", instance.image_path))

class ImageType(models.Model):
    name = models.CharField(max_length=255, db_index=True, unique=True)
    description = models.CharField(max_length=512, null=True)
    date_added = models.DateTimeField(auto_now_add=True, editable=False)
    last_modified = models.DateTimeField(auto_now=True, editable=False)

    def __unicode__(self):
        return u'%s - %s' % (self.name, self.description)

    class Meta:
        get_latest_by = "last_modified"
        ordering = ["name"]

class ImageDB(models.Model):
    #parent_image = models.ForeignKey('self', null=True, blank=True, related_name='child_image_set')
    #series = models.ForeignKey(Series)
    image_type = models.ForeignKey(ImageType)
    language = models.ForeignKey(Language)
    image_path = models.CharField(max_length=255, db_index=True, unique=True)
    image_file = models.ImageField(upload_to=get_image_path, max_length=255, null=True)
#    thumbnail_path = models.CharField(max_length=255, db_index=True, null=True)
    date_added = models.DateTimeField(auto_now_add=True, editable=False)
    last_modified = models.DateTimeField(auto_now=True, editable=False)

    def __unicode__(self):
        return u'%s - %s' % (self.image_type, self.image_path)

    class Meta:
        get_latest_by = "last_modified"
        ordering = ["image_type", "image_path"]

class Genre(models.Model):
    name = models.CharField(max_length=50, db_index=True, unique=True)
    description = models.CharField(max_length=255, null=True)
    date_added = models.DateTimeField(auto_now_add=True, editable=False)
    last_modified = models.DateTimeField(auto_now=True, editable=False)

    def __unicode__(self):
        return u'%s - %s' % (self.name, self.description)

    class Meta:
        get_latest_by = "last_modified"
        ordering = ["name"]

class Series(models.Model):
    id = models.IntegerField(primary_key=True)
    Actors = models.TextField(null=True)
    Airs_DayOfWeek = models.CharField(null=True, max_length=45)
    Airs_Time =  models.CharField(null=True, max_length=45)
    ContentRating = models.CharField(null=True, max_length=45)
    FirstAired = models.CharField(null=True, max_length=100)
#    Genre = models.CharField(null=True, max_length=255)
    genres = models.ManyToManyField(Genre)
    IMDB_ID = models.CharField(null=True, unique=True, max_length=25)
    language = models.ForeignKey(Language)
    Network = models.CharField(null=True, max_length=100)
    NetworkID = models.CharField(null=True, max_length=45)
    Overview = models.TextField(null=True)
    Rating = models.CharField(null=True, max_length=45)
    Runtime = models.CharField(null=True, max_length=100)
    SeriesID = models.CharField(null=True, max_length=45)
    SeriesName = models.CharField(max_length=255, db_index=True)
    Status = models.CharField(null=True, max_length=100)
    added = models.CharField(null=True, max_length=45)
    addedBy = models.CharField(null=True, max_length=45)
    banner = models.ForeignKey('ImageDB', null=True, related_name='child_banner_set')
#    banner = models.CharField(null=True, max_length=255)
    fanart = models.ForeignKey('ImageDB', null=True, related_name='child_fanart_set')
#    fanart = models.CharField(null=True, max_length=255)
    lastupdated = models.PositiveIntegerField(null=True)
    poster = models.ForeignKey('ImageDB', null=True, related_name='child_poster_set')
#    poster = models.CharField(null=True, max_length=255)
    zap2it_id = models.CharField(null=True, unique=True, max_length=12)
    date_added = models.DateTimeField(auto_now_add=True, editable=False)
    last_modified = models.DateTimeField(auto_now=True, editable=False)
    
    def _get_seriesid(self):
        return self.id
    seriesid = property(_get_seriesid)
    
    def __unicode__(self):
        return u'%s' % self.SeriesName

    def _get_image(self):
        return self.poster
    image = property(_get_image)

    class Meta:
        ordering = ["SeriesName",]
        get_latest_by = "last_modified"

class Season(models.Model):
    id = models.IntegerField(primary_key=True)
    series =  models.ForeignKey(Series)
    season_number = models.PositiveIntegerField(default=0)
    #date_added = models.DateTimeField(auto_now_add=True, editable=False)
    last_modified = models.DateTimeField(auto_now=True, editable=False)

    def __unicode__(self):
        return u'%s Season %s' % (self.series.SeriesName, self.season_number)    
    
    class Meta:
        unique_together = ("series", "season_number")
        ordering = ["series", "season_number"]
        get_latest_by = "last_modified"

class Episodes(models.Model):
    id = models.IntegerField(primary_key=True)
    season = models.ForeignKey(Season)
    def _get_season_id(self):
        return this.season.id
    seasonid = property(_get_season_id)
#    seasonid = models.PositiveIntegerField(default=0)
    EpisodeNumber = models.PositiveIntegerField(default=0)
    EpisodeName = models.CharField(null=True, max_length=255, default='unknown')
    FirstAired = models.CharField(null=True, max_length=45)
#    GuestStars = models.TextField(null=True)
    gueststars = models.ManyToManyField('GuestStar')
#    Director = models.TextField(null=True)
    directors = models.ManyToManyField('Director')
#    Writer = models.TextField(null=True)
    writers = models.ManyToManyField('Writer')
    Overview = models.TextField(null=True)
    ProductionCode = models.CharField(null=True, max_length=45)
    lastupdated = models.PositiveIntegerField(null=True)
    flagged = models.PositiveIntegerField(null=True)
    DVD_discid = models.CharField(null=True, max_length=45)
    DVD_season = models.PositiveIntegerField(null=True)
    DVD_episodenumber = models.DecimalField(null=True, max_digits=11, decimal_places=1)
    DVD_chapter = models.PositiveIntegerField(null=True)
    absolute_number = models.IntegerField(null=True, max_length=3)
    filename = models.ForeignKey(ImageDB, null=True)
#    filename = models.CharField(null=True, max_length=255)

    def _get_image(self):
        return self.filename
    image = property(_get_image)

    def _get_series_id(self):
        return self.series.id

    seriesid = property(_get_series_id)
    mirrorupdate = models.CharField(null=True, max_length=20)
    IMDB_ID = models.CharField(null=True, max_length=25)
    EpImgFlag = models.IntegerField(null=True, max_length=4)
    Rating = models.CharField(null=True, max_length=45)
#    SeasonNumber = models.PositiveIntegerField(db_index=True)
    def _get_season_number(self):
        return self.season.season_number
    SeasonNumber = property(_get_season_number)
    series = models.ForeignKey(Series)
    date_added = models.DateTimeField(auto_now_add=True, editable=False)
    last_modified = models.DateTimeField(auto_now=True, editable=False)

    def __unicode__(self):
        return u'%s' % self.EpisodeName
    
    class Meta:
        #order_with_respect_to = "series"
        ordering = ["series","season", "EpisodeNumber"]
        get_latest_by = "last_modified"

#class Actors(models.Model):
#    id = models.IntegerField(primary_key=True)
#    Image = models.CharField(max_length=255, null=True)
#    Name = models.CharField(max_length=255)
#    Role = models.CharField(max_length=255)
#    SortOrder = models.IntegerField(default=0)
#    series = models.ForeignKey(Series)
#    date_added = models.DateTimeField(auto_now_add=True, editable=False)
#    last_modified = models.DateTimeField(auto_now=True, editable=False)
#    
#    def __unicode__(self):
#        return u'%s' % self.Name
#    
#    class Meta:
#        unique_together = ("series", "Name")
#        #order_with_respect_to = 'series'
#        ordering = ["series", "SortOrder"]
#        get_latest_by = "last_modified"

#class PersonType(models.Model):
#    name = models.CharField(max_length=30, unique=True, db_index=True)
#    description = models.CharField(max_length=255, null=True)
#    date_added = models.DateTimeField(auto_now_add=True, editable=False)
#    last_modified = models.DateTimeField(auto_now=True, editable=False)
#
#    def __unicode__(self):
#        return u'%s' % self.name
#
#    class Meta:
#        get_latest_by = "last_modified"
        
class Person(models.Model):
    name = models.CharField(max_length=255, db_index=True, unique=True)
#    person_type = models.ForeignKey(PersonType)
    image = models.ForeignKey(ImageDB, null=True)
    date_added = models.DateTimeField(auto_now_add=True, editable=False)
    last_modified = models.DateTimeField(auto_now=True, editable=False)

    def __unicode__(self):
        return u'%s' % self.name

    class Meta:
        abstract = True
        get_latest_by = "last_modified"
#        unique_together = ("name", "person_type")

#class Actor(models.Model):
#    Name = models.CharField(max_length=255, unique=True, db_index=True)
#    image = models.ForeignKey(ImageDB, null=True)
#    date_added = models.DateTimeField(auto_now_add=True, editable=False)
#    last_modified = models.DateTimeField(auto_now=True, editable=False)
#
#    def __unicode__(self):
#        return u'%s' % self.Name
#
#    class Meta:
#        get_latest_by = "last_modified"

class Actor(Person):
    pass

class ActorRoles(models.Model):
    series = models.ForeignKey(Series)
    actor = models.ForeignKey(Actor)
    thetvdbid = models.PositiveIntegerField(default=0, db_index=True, null=True)
    Role = models.CharField(max_length=255, null=True)
    SortOrder = models.PositiveIntegerField(default=99)
    date_added = models.DateTimeField(auto_now_add=True, editable=False)
    last_modified = models.DateTimeField(auto_now=True, editable=False)

    def __unicode__(self):
        return u'%s - %s' % (self.series.SeriesName, self.Role)

    class Meta:
        get_latest_by = "last_modified"
        unique_together = ("series", "actor")
        ordering = ["series", "SortOrder", "actor"]

class GuestStar(Person):
    pass

class Director(Person):
    pass

class Writer(Person):
    pass

#class GuestStar(models.Model):
#    actor = models.ForeignKey(Actor)
#    actor_role = models.ForeignKey(ActorRoles, null=True)
#    date_added = models.DateTimeField(auto_now_add=True, editable=False)
#    last_modified = models.DateTimeField(auto_now=True, editable=False)
#
#    def __unicode__(self):
#        return u'%s - %s' % (self.episode.EpisodeName, self.actor.Name)
#
#    class Meta:
#        get_latest_by = "last_modified"
#        #unique_together = ("episode", "actor")
#        ordering = ["actor", "actor_role"]
    
class Banners(models.Model):
    id = models.IntegerField(primary_key=True)
    series = models.ForeignKey(Series)
    BannerPath = models.CharField(max_length=255, db_index=True, unique=True)
    BannerType = models.CharField(null=True, max_length=100)
    BannerType2 = models.CharField(null=True, max_length=100)
    Colors = models.CharField(null=True, max_length=255)
    language = models.ForeignKey('Language')
    def _get_series_name(self):
        return self.Series.SeriesName
    SeriesName = property(_get_series_name)
    ThumbnailPath = models.CharField(null=True, max_length=255)
    VignettePath = models.CharField(null=True, max_length=255)
    date_added = models.DateTimeField(auto_now_add=True, editable=False)
    last_modified = models.DateTimeField(auto_now=True, editable=False)

    def __unicode__(self):
        return u'%s' % self.BannerPath
    
    class Meta:
        get_latest_by = "last_modified"
        #order_with_respect_to = "series"
        ordering = ["series", "id"]
        
#class ThumbnailTypes(models.Model):
#    name = models.CharField(max_length=30, unique=True, db_index=True)
#    description = models.CharField(max_length=255)
#    
#    def __unicode__(self):
#        return u'%s' % self.name
#    
#class Thumbnails(models.Model):
#    type = models.ForeignKey(ThumbnailTypes)
#    thumbnail_path = models.CharField(max_length=255)
#    origional_path = models.CharField(max_length=255, db_index=True)
#    
#    def __unicode__(self):
#        return u'%s' % self.thumbnail_path
#    
#    class Meta:
#        unique_together = ("type", "origional_path")
    
def do_auto_thumbnail_save(sender, instance, created, *args, **kwargs):
    """
    Create a Thumbnail out of every image to make them faster for mobile apps.
    """
    print "do_auto_thumbnail_save Start"
    try:
        if (instance.image_file != None):
            mts = settings.THETVDB_DEFAULT_MAX_THUMBNAIL_SIZE
            print "Height: %s Width: %s" % (instance.image_file.height, instance.image_file.width)
            if (instance.image_file.height > mts[0]) and (instance.image_file.width > mts[1]):
                img = Image.open(instance.image_file.path)
                img.thumbnail(mts, Image.ANTIALIAS)
                img.save(instance.image_file.path, "JPEG")
                print "Height: %s Width: %s" % (instance.image_file.height, instance.image_file.width)
                print "Converted image to thumbnail."
    except IOError, e:
        print e
    print "do_auto_thumbnail_save End"

signals.post_save.connect(do_auto_thumbnail_save, sender=ImageDB)
    